<!-- 建筑群管理 -->
<template>
  <div class="app-container">
    <TopMenu v-if="showTopMenu" :data-list="topDataLabel" @tabsChange="tabsChange"/>
    <div class="main-info-container">
      <!-- 查询和其他操作 -->
      <div class="filter-container">
        <el-form ref="listQuery" :inline="true" :model="listQuery" class="form-bottom-line">
          <el-form-item v-if="showTopMenu" label="选择单位:">
            <el-select v-model="listQuery.corp_id" clearable filterable allow-create default-first-option autocomplete="off" placeholder="请输入单位名称" @change="companyChange" >
              <el-option v-for="item in companyList" :key="item.corp_id" :label="item.name" :value="item.corp_id" />
            </el-select>
          </el-form-item>
          <el-form-item label="建筑群名称：" prop="name">
            <el-select v-if="showTopMenu" v-model="listQuery.name" clearable filterable allow-create default-first-option autocomplete="off" placeholder="请输入单位名称" @change="companyChange" >
              <el-option v-for="item in parkList" :key="item.name" :label="item.name" :value="item.name" />
            </el-select>
            <el-input v-else v-model="listQuery.name" clearable placeholder="请输入建筑群名称" autocomplete="off"/>
          </el-form-item>
          <el-form-item label="地址：" prop="address">
            <el-input v-model="listQuery.address" clearable placeholder="请输入地址" autocomplete="off"/>
          </el-form-item>
          <el-form-item>
            <el-button v-permission="['v1/parks/index']" type="primary" size="small" icon="el-icon-search" @click="handleFilter" >查询</el-button>
            <el-button v-permission="['v1/parks/create']" type="primary" size="small" icon="el-icon-plus" @click="handleAdd">添加建筑群</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 查询结果         max-height="362"-->
      <el-table
        v-loading="listLoading"
        ref="table"
        :data="list"
        row-key="index"
        class="tableDetail"
        size="small"
        element-loading-text="正在查询中。。。"
        stripe
        border
        el-table-column
        fit
        highlight-current-row
        @expand-change="expandChange">
        <el-table-column type="expand">
          <template slot-scope="props">
            <!-- v-loading="listDetailLoading" -->
            <el-table :data="props.row.detail" size="small" stripe border el-table-column fit highlight-current-row row-key="id">
              <el-table-column align="center" label="建筑名称" prop="">
                <template slot-scope="scopeTwo"><span class="hink" @click="buildEdit(scopeTwo.row)">{{ scopeTwo.row.name }}</span></template>
              </el-table-column>
              <el-table-column align="center" label="建筑高度(m)" prop="">
                <template slot-scope="scopeTwo">{{ scopeTwo.row.storey_height }}</template>
              </el-table-column>
              <el-table-column align="center" label="地上楼层" prop="">
                <template slot-scope="scopeTwo">{{ scopeTwo.row.above_ground_floor }}</template>
              </el-table-column>
              <el-table-column align="center" label="地下楼层" prop="">
                <template slot-scope="scopeTwo">{{ scopeTwo.row.under_ground_floor }}</template>
              </el-table-column>
              <el-table-column align="center" label="状态" width="100" class-name="small-padding fixed-width">
                <template slot-scope="scopeTwo">
                  <!-- <el-switch v-if="scopeTwo.row.is_forbidden" v-model="scopeTwo.row.is_forbidden" active-text="启用" inactive-text="禁用" active-color="#109008" inactive-color="#f2473f" @click.native.prevent="iconQiyongDetail(props.row.index, scopeTwo.$index, scopeTwo.row)"/> -->
                  <el-switch v-permission="['v1/buildings/enable']" v-model="scopeTwo.row.is_forbidden" active-text="启用" inactive-text="禁用" active-color="#109008" inactive-color="#f2473f" @click.native.prevent="iconQiyongDetail(props.row.index, scopeTwo.$index, scopeTwo.row)"/>
                  <!-- <el-switch v-if="!scopeTwo.row.is_forbidden" v-model="scopeTwo.row.is_forbidden" active-text="启用" inactive-text="禁用" active-color="#109008" inactive-color="#f2473f" @click.native.prevent="iconTingzhiDetail(props.row.index, scopeTwo.$index, scopeTwo.row)"/> -->
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column align="center" label="建筑群名称" prop="name" width="120">
          <template slot-scope="scope"><span class="hink" @click="handleEdit(scope.row)">{{ scope.row.name }}</span></template>
        </el-table-column>
        <el-table-column align="center" width="300" label="地区/详细地址" prop="address">
          <template slot-scope="scope">{{ scope.row.address }}</template>
        </el-table-column>
        <el-table-column align="center" label="所属单位" prop="corp_name"/>
        <el-table-column align="center" label="建筑总数" prop="total_building" width="80">
          <template slot-scope="scope"><span class="hink" @click="toBuildPage(scope.row)">{{ scope.row.added_total_building }}/{{ scope.row.total_building }}</span></template>
        </el-table-column>
        <el-table-column align="center" label="联系人" prop="link_user" width="80"/>
        <el-table-column align="center" label="联系电话" prop="link_user_mobile" width="100"/>
        <el-table-column align="center" label="状态" width="100" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <!-- 启用 -->
            <el-switch v-permission="['v1/parks/enable']" v-model="scope.row.is_forbidden" active-text="启用" inactive-text="禁用" active-color="#109008" inactive-color="#f2473f" @click.native.prevent="iconQiyong(scope.$index, scope.row)"/>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
      <formPark
        :dialog-form="dialogForm"
        :dialog-type="dialogType"
        :dialog-visible.sync="dialogVisible"
        @getCancel="handleCancel"
        @closeBindWarnStandard="handleCloseBindWarnStandard"
        @submitForm="submitForm"/>
      <formBuild
        :dialog-form="dialogFormBuild"
        :dialog-type="dialogTypeBuild"
        :dialog-visible.sync="dialogVisibleBuild"
        @getCancel="handleCancelBuild"
        @closeBindWarnStandard="handleCloseBindWarnStandardBuild"
        @submitForm="submitFormBuild"/>
    </div>
  </div>
</template>
<script>
import { getSocialUnit } from '@/api/company'
import { parksList, buildList, parksUpdate, buildUpdate } from '@/api/park'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import formPark from './components/formPark.vue'
import formBuild from './components/formBuild.vue'
import TopMenu from '@/components/TopMenu' // 顶部菜单
import checkPermission from '@/utils/permission' // 权限判断函数

export default {
  name: 'Park',
  components: {
    Pagination,
    formPark,
    formBuild,
    TopMenu
  },
  data() {
    return {
      topDataLabel: {
        data: []
      },
      // 新增修改建筑群弹窗信息
      dialogForm: {
        corp_id: '',
        name: '',
        province: '',
        city: '',
        district: '',
        address: '',
        plan: '',
        latitude: '',
        longitude: '',
        link_user: '',
        link_user_mobile: '',
        total_building: '',
        is_forbidden: ''
      },
      dialogType: '添加',
      dialogVisible: false,
      // 修改建筑信息
      dialogFormBuild: {
        name: '', // 建筑名称
        province: '', // 省
        city: '', // 市
        district: '', // 区
        address: '', // 详细地址
        longitude: '', // 经度
        latitude: '', // 纬度
        park_id: '', // 建筑群id
        park_name: '', // 建筑群名
        storey_height: 0, // 建筑高度
        above_ground_area: 0, // 地上面积
        under_ground_area: 0, // 地下面积
        above_ground_floor: 0, // 地上层数
        under_ground_floor: 0, // 地下层数
        building_type: 0, // 建筑类型
        building_property: '', // 使用性质
        structure: '', // 建筑物结构
        fireproof_endurance_rating: 0, // 耐火等级
        danger_classes: 0, // 建造时间
        acceptance_at: '' // 验收时间
      },
      dialogTypeBuild: '修改',
      dialogVisibleBuild: false,
      // 表格信息
      list: [],
      total: 0,
      listLoading: false,
      listDetailLoading: false,
      corp_id: '',
      corp_name: '',
      listQuery: {
        page: 1,
        offset: 8,
        corp_id: '',
        corp_name: '',
        name: '',
        address: ''
      },
      getRowKeys(row) {
        return row.id
      },
      parkList: [],
      companyList: [],
      showTopMenu: false
    }
  },
  created() {
    // 如果是社会单位
    if (sessionStorage.getItem('corpType') && sessionStorage.getItem('corpType') === '2') {
      this.showTopMenu = false
    } else {
      this.showTopMenu = true
      this.getCompanyList()
    }
    this.getList()
  },
  methods: {
    // 列表查询
    checkPermission,
    getList() {
      this.listLoading = true
      const $table = this.$refs.table
      const that = this
      this.list.map((item) => {
        $table.toggleRowExpansion(item, false)
      })
      // $table.toggleRowExpansion(row)
      this.dialogForm.corp_id = this.dialogForm.corp_id
      parksList(this.listQuery)
        .then(response => {
          const data = response.data
          if (data.code === 40000) {
            that.list = []
            response.data.data.data.forEach(function(value, index, array) {
              array[index].is_forbidden = array[index].is_forbidden === 2
              array[index].detail = []
              array[index].index = index
              that.list.push(array[index])
            })
            that.total = parseInt(response.data.data.total_count)
          }
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    // 单位下拉框查询
    getCompanyList() {
      const that = this
      getSocialUnit()
        .then(response => {
          const data = response.data
          if (data.code === 40000) {
            that.companyList = []
            if (that.companyList && response.data.data.length > 0) {
              that.companyList = response.data.data
              that.showTopMenu = true
            }
          } else if (response.data.code === 40003 && response.data.message === '权限验证失败!') {
            that.showTopMenu = false
          } else {
            that.$message.warning(response.data.message)
          }
        })
        .catch(() => {
          this.companyList = []
        })
    },
    // 获取建筑群列表
    getParksList() {
      const that = this
      var listQuery = {
        page: 1,
        offset: 1000,
        corp_id: that.listQuery.corp_id
      }
      parksList(listQuery)
        .then(response => {
          if (response.data.code === 40000) {
            that.parkList = []
            response.data.data.data.forEach(function(value, index, array) {
              array[index].index = index
              that.parkList.push(array[index])
            })
            console.log(that.parkList)
          }
        })
        .catch(() => {
          this.parkList = []
        })
    },
    // 单位下拉框
    companyChange(value) {
      if (value !== '') {
        var select = {}
        this.companyList.forEach(function(data, index, array) {
          if (value === array[index].corp_id) {
            select = array[index]
          }
        })
        if (this.listQuery.corp_id) {
          this.getParksList()
        }
        if (this.topDataLabel.data.indexOf(select.name) === -1) {
          this.topDataLabel.data.push(select.name)
        }
      } else {
        this.listQuery.name = ''
        this.parkList = []
      }
    },
    // 查询
    handleFilter(row) {
      this.listQuery.page = 1
      this.getList()
    },
    // 启用建筑群
    iconQiyong(index, data) {
      const is_forbidden = data.is_forbidden // 保存点击之后v-modeld的值(true，false)
      data.is_forbidden = !data.is_forbidden // 保持switch点击前的状态
      const that = this
      var flag = is_forbidden ? '启用' : '禁用'
      this.$confirm('此操作将' + flag + '该行数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      }).then(() => {
        var params = {
          park_id: data.park_id,
          is_forbidden: is_forbidden ? 2 : 1
        }
        parksUpdate(params)
          .then((res) => {
            const data = res.data
            if (data.code === 40000) {
              that.getList()
              that.$message.success(data.message)
            } else {
              that.$message.warning(data.message)
            }
            that.getList()
          })
          .catch(() => {
            that.getList()
          })
      }).catch(() => {
        that.getList()
      })
    },
    // 启用建筑
    iconQiyongDetail(index, indexDetail, data) {
      const is_forbidden = data.is_forbidden // 保存点击之后v-modeld的值(true，false)
      data.is_forbidden = !data.is_forbidden // 保持switch点击前的状态
      const that = this
      var flagText = is_forbidden ? '启用' : '停用'
      this.$confirm('此操作将' + flagText + '该行数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var params = {
          building_id: data.building_id,
          is_forbidden: is_forbidden ? '2' : '1'
        }
        buildUpdate(params)
          .then((res) => {
            const data = res.data
            if (data.code === 40000) {
              that.$message.success(data.message)
            } else {
              that.$message.warning(data.message)
            }
            that.getList()
          })
          .catch(() => {
            that.getList()
          })
      }).catch(() => {
        that.getList()
      })
    },
    // 停用建筑
    iconTingzhiDetail(index, indexDetail, data) {
      const that = this
      var params = {
        uuid: data.uuid
      }
      buildUpdate(params)
        .then((res) => {
          const data = res.data
          if (data.code === 40000) {
            that.getList()
            that.$message.success(data.messageContent)
          } else {
            that.$message.warning(data.messageContent)
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 添加建筑群
    handleAdd() {
      this.dialogForm = {
        name: '',
        province: '31000',
        city: '31001',
        district: '31002',
        address: '',
        latitude: '',
        longitude: '',
        total_building: '',
        plan: '',
        corp_id: this.corp_id,
        corp_name: this.corp_name,
        link_user: '',
        link_user_mobile: ''
      }
      this.dialogType = '添加'
      this.dialogVisible = true
    },
    // 修改建筑群
    handleEdit(data) {
      this.dialogForm = JSON.parse(JSON.stringify(data))
      if (this.dialogForm.is_forbidden === true) {
        this.dialogForm.is_forbidden = '2'
      } else {
        this.dialogForm.is_forbidden = '1'
      }
      this.dialogForm.plan = this.dialogForm.plan ? this.dialogForm.plan : ''
      console.log(JSON.stringify(this.dialogForm))
      this.dialogVisible = true
      this.dialogType = '修改'
    },
    // 添加弹窗确认
    submitForm(formName) {
      this.getList()
      this.dialogVisible = false
    },
    handleCancel() {
      this.dialogVisible = false
    },
    // 关闭弹窗
    handleCloseBindWarnStandard() {
      this.dialogVisible = false
    },
    // 修改建筑
    buildEdit(row) {
      this.dialogFormBuild = JSON.parse(JSON.stringify(row))
      this.dialogVisibleBuild = true
      delete this.dialogFormBuild['is_forbidden']
      this.dialogTypeBuild = '修改'
      this.dialogFormBuild.danger_classes = this.dialogFormBuild.danger_classes + ''
      this.dialogFormBuild.building_type = this.dialogFormBuild.building_type + ''
      this.dialogFormBuild.building_property = this.dialogFormBuild.building_property + ''
      this.dialogFormBuild.structure = this.dialogFormBuild.structure + ''
      this.dialogFormBuild.fireproof_endurance_rating = this.dialogFormBuild.fireproof_endurance_rating + ''
    },
    // 添加弹窗确认
    submitFormBuild(formName) {
      this.getList()
      this.dialogVisibleBuild = false
    },
    handleCancelBuild() {
      this.dialogVisibleBuild = false
    },
    // 关闭弹窗
    handleCloseBindWarnStandardBuild() {
      this.dialogVisibleBuild = false
    },
    expandChange(row, expandedRows) {
      this.listDetailLoading = true
      const that = this
      const i = row.index
      const params = {
        park_id: row.park_id
      }
      buildList(params)
        .then(response => {
          if (response.data.code === 40000) {
            that.list[i].detail = []
            response.data.data.data.forEach(function(value, index, array) {
              array[index].is_forbidden = array[index].is_forbidden === 2
              that.list[i].detail.push(array[index])
            })
          }
          that.listDetailLoading = false
        })
        .catch(() => {
          that.listDetailLoading = false
        })
    },
    toBuildPage(row) {
      this.$router.push({
        name: 'buildManage',
        params: {
          parkData: row
        }
      })
    },
    // 顶部切换监听
    tabsChange(value) {
      const that = this
      this.companyList.forEach(function(data, index, array) {
        if (value === array[index].name) {
          that.listQuery.corp_id = array[index].corp_id
        }
      })
      this.getList()
    },
    setTimeoutFn() {
      const that = this
      this.listLoading = true
      setTimeout(function() {
        that.listLoading = false
      }, 1000)
    }
  }
}
</script>
